package treeedit;

public class NBTree {
	private static final String EMPTY_STRING = "E";
	public static final NBTree EMPTY = new NBTree(EMPTY_STRING);

	private String name;
	private NBTree left;
	private NBTree right;

	/**
	 * This class represent a Normalized Binary Tree data structure. Has name as
	 * string and left, right child as trees also.
	 */
	public NBTree(String name) {
		this.name = name;
	}

	public NBTree() {
	}

	/**
	 * This constructor create a NBTree from a standard Tree.
	 */
	public NBTree(Tree tree) {
		name = tree.getName();

		if (tree.isLeaf()) {
			left = right = EMPTY;
		} else {
			NBTree lastT = null;
			for (Tree child : tree.getChildren()) {
				if (lastT == null) { // First child
					left = lastT = new NBTree(child);
					right = EMPTY;
				} else { // Next children
					lastT.right = new NBTree(child);
					lastT = lastT.right;
				}
			}
		}
	}

	public boolean isEmpty() {
		return (left == null && right == null) || EMPTY_STRING.equals(name);
	}

	public String getName() {
		return name;
	}

	public NBTree getLeft() {
		return left;
	}

	public NBTree getRight() {
		return right;
	}

	/**
	 * Get the string representation of a binary branch rooted in this node.
	 */
	public String getBranchString() {
		return name + left.name + right.name;
	}

	/**
	 * Get the hash of string representation of a binary branch rooted in this
	 * node.
	 */
	public int getBranchHash() {
		return getBranchString().hashCode();
	}
}
